<?php

namespace App\Controller\Home;

use App\Controller\Example\BonusExample;
use App\Controller\Example\PoolExample;
use App\Controller\Example\SettlementExample;
use App\Controller\Example\UserExample;
use App\Models\ConfigModel;
use App\Models\Conn;
use App\Models\PoolModel;
use App\Models\SettlementModel;
use App\Models\UsersModel;
use Config\Config;
use Core\Common\Common;
use Core\Enums\DigitEnum;
use Core\Enums\FundsEnum;
use Core\Enums\FundsGenreEnum;
use Core\Result\Result;
use Core\Utils\Utils;

class Sett
{

    /**
     * 结算返佣
     * */
    public static function customers($id){
        $conn = new Conn();
        $SettlementExample = Common::assemble(new SettlementExample(),SettlementModel::getSettlement($conn,$id));
        if(empty($SettlementExample->id)){
            $conn->close();
            return true;
        }
        $UserExample = Common::assemble(new UserExample(),UsersModel::getUserInsideId($conn, $SettlementExample->uid));
        if(empty($UserExample->pid)){
            $conn->close();
            return true;
        }
        $BIG_REWARD = ConfigModel::getConfigSingleValName($conn, Config::BIG_REWARD);//大区奖励
        $bigReward = $SettlementExample->money * $BIG_REWARD;//大区奖励
        $SettlementExample->state = 2;
        $SettlementExample->endtime = date('Y-m-d H:i:s', time());
        $bonus = $devote = $bigNums = 0;
        $UserExampleAllPid = UsersModel::getUserSuperiorAllPid($conn, $UserExample->pid);
        $userSuperiorAllIds = UsersModel::getUserSuperiorAllIds($conn, $UserExample->id);
        $PoolExample = Common::assemble(new PoolExample(), PoolModel::getPoolInside($conn));
        $bigIds = $maxUserid = null;
        $upBigSql = "peer_reward = case id";
        $fundsSql ="INSERT INTO `funds`(`uid`, `sn`, `type`, `amount`, `balance`, `notes`, `genre`) VALUES";
        foreach ($UserExampleAllPid as $value){
            $UserExampleAll = Common::assemble(new UserExample(), $value);
            $userInsideBigId = UsersModel::getUserInsideBig($conn, $UserExampleAll->id);//查询大区id
            //大区结算
            if($UserExampleAll->capping > DigitEnum::ZERO){
                //if($userInsideBigId == $maxUserid || $maxUserid == null){
                /*$award = round($bigReward * 0.5,3);//佣金
                $bonus += round($bigReward * 0.35,3);//贡献分红池35%
                $devote += round($bigReward * 0.15,3);//贡献抽奖池15%*/
                $upBigSql .= " when $UserExampleAll->id then `peer_reward` + $bigReward";
                $fundsBalance = $UserExampleAll->peer_reward + $bigReward;
                $fundsSql .="(";
                $fundsSql .=$UserExampleAll->id.",'".$SettlementExample->no."','".FundsEnum::SALESBONUS."',".$bigReward.",$fundsBalance,'".FundsEnum::SALESBONUSZHCN."',".FundsGenreEnum::SALES;
                $fundsSql .="),";
                $bigIds .= $UserExampleAll->id.",";
                $bigNums++;
                //}
                //小区先不管 领取算
            }
            //$maxUserid = $UserExampleAll->id;
        }
        if($bigIds){
            $conn->shiwuStart();
            $bigIds = rtrim($bigIds,",");
            $fundsSql = rtrim($fundsSql,",");
            $upBigSql .= " end";
            $upBigReward = "update `users` set $upBigSql where `id` in($bigIds)";
            $executeConn = $conn->executeConn($upBigReward);
            $executeConn1 = $conn->executeConn($fundsSql);
            if($executeConn != $bigNums || $executeConn1 != $bigNums){
                $SettlementExample->state = 3;
                $conn->shiwuRollback();
                Utils::writeSettLog("结算ID：".$SettlementExample->id.",大区失败语句：".$upBigReward."\r\n");
            }else{
                $conn->shiwuEnd();
            }
        }
        if($userSuperiorAllIds){
            $conn_jy = new Conn();
            $upUserSach = "update `users` set `sach` = `sach` + $SettlementExample->money where `id` in($userSuperiorAllIds)";
            $conn_jy->shiwuStart();
            $upUserSachExe = $conn_jy->executeConn($upUserSach);
            if($upUserSachExe == -1){
                $SettlementExample->state = 4;
                $conn_jy->shiwuRollback();
                Utils::writeSettLog("结算ID：".$SettlementExample->id.",业绩失败语句：".$upUserSach."\r\n");
            }else{
                $conn_jy->shiwuEnd();
            }
        }
        /*if($bonus > 0 || $devote > 0){
            $conn_pool = new Conn();
            $bonusBalance = $PoolExample->bonus + $bonus;
            $devoteBalance = $PoolExample->devote + $devote;
            $upPoolsql = "UPDATE `pool` SET `bonus` = `bonus` + $bonus,`devote` = `devote` + $devote WHERE `id` = $PoolExample->id and `bonus` = $PoolExample->bonus and `devote` = $PoolExample->devote";
            $conn_pool->shiwuStart();
            var_dump($upPoolsql);
            var_dump("\r\n");
            $upPoolExe = $conn_pool->executeConn($upPoolsql);
            $writeFundsSystem = Funds::writeFundsSystem($conn, $SettlementExample->no, FundsEnum::CONTRIBUTIONDIVIDENDS, $bonus,$bonusBalance, "系统");
            $writeFundsSystem1 = Funds::writeFundsSystem($conn, $SettlementExample->no, FundsEnum::LOTTERYDIVIDENDS, $devote,$devoteBalance, "系统");
            if($upPoolExe != DigitEnum::ONE || $writeFundsSystem != DigitEnum::ONE || $writeFundsSystem1 != DigitEnum::ONE){
                $conn_pool->shiwuRollback();
                $SettlementExample->state = 5;
                Utils::writeSettLog("结算ID：".$SettlementExample->id.",奖池失败语句：".$upPoolsql."\r\n");
            }else{
                $conn_pool->shiwuEnd();
            }
        }*/
        $editInside = SettlementModel::editInside(new Conn(), $SettlementExample);
        if($editInside != DigitEnum::ONE){
            Utils::writeSettLog("结算ID：".$SettlementExample->id.",结算失败状态：".$SettlementExample->state."\r\n");
        }
        $conn->close();
        return true;
    }
    /**
     * 新结算
     * */
    public static function settlement($uid,$settId,$orderMoney,$serial){
        $conn = new Conn();
        $userSuperiorAllIds = UsersModel::getUserSuperiorAllIds($conn, $uid);
        $SettlementExample = new SettlementExample();
        $SettlementExample->id = $settId;
        $SettlementExample->state = 2;
        $SettlementExample->endtime = date('Y-m-d H:i:s', time());
        $Settlement = SettlementModel::getSettlement($conn,$settId);
        //业绩更新
        if($userSuperiorAllIds){
            $conn_jy = new Conn();
            $upUserSach = "update `users` set `sach` = `sach` + $orderMoney where `id` in($userSuperiorAllIds)";
            $conn_jy->shiwuStart();
            $upUserSachExe = $conn_jy->executeConn($upUserSach);
            if($upUserSachExe == -1){
                $SettlementExample->state = 4;
                $conn_jy->shiwuRollback();
                Utils::writeSettLog("结算ID：".$SettlementExample->id.",业绩失败语句：".$upUserSach."\r\n");
            }else{
                $conn_jy->shiwuEnd();
            }
        }
        /*if($SettlementExample->state == 2){
            $userSuperiorAllPid = UsersModel::getUserSuperiorAllPid($conn, $uid);
            $BIG_REWARD = ConfigModel::getConfigSingleValName($conn, Config::BIG_REWARD);//大区奖励
            $SMALL_REWARD = ConfigModel::getConfigSingleValName($conn, Config::SMALL_REWARD);//大区奖励
            $maxUserid = null;
            $int = 0;
            $bigReward = $orderMoney * $BIG_REWARD;
            $smallReward = $orderMoney * $SMALL_REWARD;
            $conn_xs = new Conn();
            switch ($Settlement["type"]){
                case 2 :
                    $fundsType = FundsEnum::DIRECTSALESBONUS;
                    $fundsNotes = FundsEnum::DIRECTSALESBONUSZHCN;
                    break;
                default:
                    $fundsType = FundsEnum::SALESBONUS;
                    $fundsNotes = FundsEnum::SALESBONUSZHCN;
                    break;
            }
            foreach ($userSuperiorAllPid as $value){
                $Reward = 0;
                $UserExampleAll = Common::assemble(new UserExample(), $value);
                $userInsideBigId = UsersModel::getUserInsideBig($conn_xs, $value["id"]);//查询大区id  108656  108656
                if($userInsideBigId == $maxUserid || $maxUserid == null){
                    //大区
                    if($int <= 50 && $int >0 && $UserExampleAll->capping >=99){
                        $Reward = $bigReward;
                    }
                }else{
                    //小区
                    if($userInsideBigId != $maxUserid && $UserExampleAll->capping >=99)
                        $Reward = $smallReward;
                }

                if($Reward > DigitEnum::MINIMUM){
                    $SettlementExample->total += $Reward;
                    $conn_xs->shiwuStart();
                    if(UsersModel::editUserPeerRewardInside($conn_xs,$Reward,$UserExampleAll) != DigitEnum::ONE || Funds::writeFundsSale($conn_xs,$UserExampleAll->id,$serial,$fundsType,$Reward,$UserExampleAll->peer_reward + $Reward,$fundsNotes) != DigitEnum::ONE){
                        $conn_xs->shiwuRollback();
                        $SettlementExample->state = 5;
                        Utils::writeSettLog("结算用户ID：".$UserExampleAll->id.",失败金额：".$Reward.",单号：".$serial."\r\n");
                        break;
                    }else{
                        $conn_xs->shiwuEnd();
                    }
                }
                $maxUserid = $value["id"];
                $int++;
            }
        }*/
        $editInside = SettlementModel::editInside($conn, $SettlementExample);
        if($editInside != DigitEnum::ONE){
            Utils::writeSettLog("结算ID：".$SettlementExample->id.",结算失败状态：".$SettlementExample->state."\r\n");
        }
        return true;
    }
    /**
     * 周分红（外接）
     * */
    public function WeeklyDividends(){
        $bonusExample = new BonusExample();
        $bonusExample->week = date("Y",time()).date("W",time());
        $bonusExample->scale = 0.03;
        $bonusExample->num = 0;
        $bonusExample->state = 1;
        $conn = new Conn();
        $sql="SELECT `id` FROM `bonus` WHERE `week` = $bonusExample->week limit 1";
        $readConn = $conn->readConn($sql);
        if($readConn){
            Utils::writeSettLog("本周重复分红：".$bonusExample->week.",执行时间：".time()."\r\n");
            Result::error("本周已经分红,请勿重复提交");
        }
        $bonusExample->capping = $conn->readConn("SELECT sum(`capping`) as total FROM `users` WHERE `capping` >=3999 AND `id` > 10000")["total"];
        $userSql = "SELECT `id`,`push_reward`,`capping` FROM `users` WHERE `capping` >=3999 AND `id` > 10000";
        $userArr = $conn->readConn($userSql, true);
        $pool = $conn->readConn("SELECT `bonus` FROM `pool` WHERE `id` = 1")["bonus"];
        $fundsSql = $upBigSql = $bigIds = null;
        $bigNums = 0;
        if($bonusExample->capping && $pool > 0){
            $bonusExample->cny = $bonusExample->capping * $bonusExample->scale;
            $bonus = $pool - $bonusExample->cny;
            if($bonusExample->cny > $pool){
                $bonusExample->cny = $pool;
                $bonusExample->scale  = $bonusExample->cny / $bonusExample->capping;
                $bonus = 0;
            }
            $upBigSql = "push_reward = case id";
            $fundsSql ="INSERT INTO `funds`(`uid`, `sn`, `type`, `amount`, `balance`, `notes`, `genre`) VALUES";
            foreach ($userArr as $value){
                $UserExampleAll = Common::assemble(new UserExample(), $value);
                $bigReward = $UserExampleAll->capping * $bonusExample->scale;
                if($bigReward > DigitEnum::ZERO){
                    $upBigSql .= " when $UserExampleAll->id then `push_reward` + $bigReward";
                    $fundsBalance = $UserExampleAll->push_reward + $bigReward;
                    $fundsSql .="(";
                    $fundsSql .=$UserExampleAll->id.",'".$bonusExample->week."','".FundsEnum::WEEKLYDIVIDENDS."',".$bigReward.",$fundsBalance,'".FundsEnum::WEEKLYDIVIDENDSZHCN."',".FundsGenreEnum::WEEKLY;
                    $fundsSql .="),";
                    $bigIds .= $UserExampleAll->id.",";
                    $bigNums++;
                }
            }
        }
        $conn->shiwuStart();
        if($bigIds){
            $bigIds = rtrim($bigIds,",");
            $fundsSql = rtrim($fundsSql,",");
            $upBigSql .= " end";
            $upBigReward = "update `users` set $upBigSql where `id` in($bigIds)";
            $executeConn = $conn->executeConn($upBigReward);
            $executeConn1 = $conn->executeConn($fundsSql);
            if($executeConn != $bigNums || $executeConn1 != $bigNums){
                $bonusExample->state = 2;
                $conn->shiwuRollback();
                Utils::writeSettLog("结算周期：".$bonusExample->week.",失败语句：".$upBigReward.$fundsSql."\r\n");
                Result::error("周分红失败");
            }
            $bonusExample->num = $bigNums;
            $upPoolSql = "UPDATE `pool` SET `bonus` = `bonus` - $bonusExample->cny WHERE `id` = 1 AND  `bonus` = $pool";
            $writeFundsSystem = Funds::writeFundsSystem($conn, $bonusExample->week, FundsEnum::CONTRIBUTIONDIVIDENDS, -$bonusExample->cny, $bonus, "周分红结算");
            if($conn->executeConn($upPoolSql) != 1 || $writeFundsSystem != 1){
                $bonusExample->state = 3;
                $conn->shiwuRollback();
                Utils::writeSettLog("结算周期：".$bonusExample->week.",更新奖池失败语句：".$upPoolSql.$writeFundsSystem."\r\n");
                Result::error("周分红失败");
            }
        }
        $insertSql = "insert into `bonus`(`week`,`num`,`cny`,`state`,`capping`,`scale`)value('$bonusExample->week','$bonusExample->num','$bonusExample->cny',$bonusExample->state,$bonusExample->capping,$bonusExample->scale)";
        if($conn->executeConn($insertSql) != 1){
            $conn->shiwuRollback();
            Utils::writeSettLog("结算周期：".$bonusExample->week.",写入分红失败语句：".$insertSql."\r\n");
            Result::error("周分红失败");
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * 刷新业绩专用
     * */
    public function sach(){
        exit;
        $conn = new Conn();
        $sql="select `id`,`token`,`capping`,`ach` from `users` where `id` >99990 AND `pid` <> 1 AND `capping` >0";
        $readConn = $conn->readConn($sql, true);
        $conn->shiwuStart();
        foreach ($readConn as $value){
            $userExample = new UserExample();
            $userExample->token = $value["token"];
            $userExample->svip = 1;
            $userExample->sach = UsersModel::getUserAllSumAch($conn, $value["id"]);
            //$userExample->share_rewards = UsersModel::getUserInsideSmallAch($conn, $value["id"]);
            echo $value["id"]."：";
            echo $userExample->sach."\r\n";
            //var_dump($userExample->share_rewards);
            if(UsersModel::upUserInside($conn,$userExample) > DigitEnum::ONE){
                $conn->shiwuRollback();
                Result::error("失败");
            }
        }
        $conn->shiwuEnd();
        Result::success("ok");
    }
    /**
     * 3月1号之前账号清理
     * */
    public function reg(){
        $conn = new Conn();
        $sql="SELECT * FROM `users` where capping =3999 and id >100000";
        $readConn = $conn->readConn($sql,true);
        $sql2="SELECT GROUP_CONCAT(`member_id`) as ids FROM `shop_goods_order` WHERE type = 1 and order_price = 3999";
        $readConn2 = $conn->readConn($sql2)["ids"];
        $explode = explode(",", $readConn2);
        foreach ($readConn as $value){
            if(in_array($value["id"],$explode)){
            }else{
                echo $value["username"]."\r\n";
            }
        }
        exit;
        //$conn->shiwuStart();
        $SettlementExample = new SettlementExample();
        foreach ($readConn as $value){
            $sel = "select `sku_id` from `shop_goods_order` where `order_no` = '$value[no]'";
            $sku_id = $conn->readConn($sel)["sku_id"];
            $sel2 = "select `sku_cost_price` from `shop_goods_sku` where `sku_id` = $sku_id";
            $sku_cost_price= $conn->readConn($sel2)["sku_cost_price"];
            if($sku_cost_price >0 ){
                $SettlementExample->id = $value["id"];
                $SettlementExample->cost = $sku_cost_price;
                echo $value["no"]."：".$sku_cost_price."\r\n";
            }
          /* $upsql2 = "update `users` set `svip` = 2 where `id` = $value[id]";
           $executeConn2 = $conn->executeConn($upsql2);
           echo $value["id"]."：".$num."\r\n";
           //var_dump($userExample->share_rewards);
           if($executeConn2 != DigitEnum::ONE){
               //$conn->shiwuRollback();
               Result::error($upsql2);
           }*/
            SettlementModel::editInside($conn, $SettlementExample);
        }
        //$conn->shiwuEnd();
        Result::success("ok");
    }
}
